var c = document.getElementById('c'),
		ctx = c.getContext('2d'),
		cw = document.getElementById('canvasWarp'),
		bg_img = new Image(),
		pointer_img = new Image(),
		flag_s_red = new Image(),
		flag_b_red = new Image(),
		flag_s_green = new Image(),
		flag_b_green = new Image(),
		flagArray = [];
		imgCount = 6,
		config = [],
		checkpoint = 1,
    zoomX = 1, zoomY = 1;
// 初始化画布与屏幕配置
function onWindowResize () {
  c.width = window.screen.width * (window.devicePixelRatio || 1);
  c.height = window.screen.height * (window.devicePixelRatio || 1);
  zoomX = window.screen.width / c.width;
  zoomY = window.screen.height / c.height;
  cw.style.transform = 'scale('+ zoomX +', ' + zoomY +')';
  var cwBr = cw.getBoundingClientRect();
  cw.style.transform = 'translate('+ (-1 * cwBr.left) +'px, '+ (-1 * cwBr.top) +'px) ' + cw.style.transform;
  config.pointer_width = c.width * .08;
  config.pointer_height = c.height * .05778;
  config.pointer_move_height = c.height * .01185
}
onWindowResize();

// 构建配置对象
function buildConfig () {
  // 第一关
  config.push({
    pointer_static_x: c.width * .11733,
    pointer_static_y: c.height * .69111
  });
  // 第二关
  config.push({
    pointer_static_x: c.width * .35733,
    pointer_static_y: c.height * .68296
  });
  // 第三关
  config.push({
    pointer_static_x: c.width * .556,
    pointer_static_y: c.height * .61852
  });
  // 第四关
  config.push({
    pointer_static_x: c.width * .80667,
    pointer_static_y: c.height * .46815
  });
  // 第五关
  config.push({
    pointer_static_x: c.width * .556,
    pointer_static_y: c.height * .45555
  });
  // 第六关
  config.push({
    pointer_static_x: c.width * .35733,
    pointer_static_y: c.height * .39185
  });
  // 第七关
  config.push({
    pointer_static_x: c.width * .11733,
    pointer_static_y: c.height * .24519
  });
  // 第八关
  config.push({
    pointer_static_x: c.width * .35733,
    pointer_static_y: c.height * .23704
  });
  // 第九关
  config.push({
    pointer_static_x: c.width * .556,
    pointer_static_y: c.height * .17333
  });
  // 第十关
  config.push({
    pointer_static_x: c.width * .78,
    pointer_static_y: c.height * .04148
  });
}

/**
 * 旗子类
 * @param color  red | green
 * @param size  s | b
 * @constructor
 */
function Flag (ops, color, size) {
  this.x = ops.x || 0;
  this.y = ops.y || 0;
  if (size === 's') {
    this.width = this.height = c.width * .07467;
  } else {
    this.width = c.width * .272;
    this.height = c.height * .04;
  }
  switch (color) {
    case 'red':
      if (size === 's') this.img = flag_s_red;
      else this.img = flag_b_red;
      break;
    case 'green':
      if (size === 's') this.img = flag_s_green;
      else this.img = flag_b_green;
      break;
    default:
      break;
  };
}
// 旗子绘制
Flag.prototype.draw = function (ctx, x, y) {
  this.x = x;
  this.y = y;
  ctx.drawImage(this.img,  this.x,  this.y, this.width, this.height);
};
// 旗子类静态属性
Flag.top_offset = c.height * .07862;

/**
 * 初始化图片资源
 * @param {Function} cb 回调函数
 */
function initImages (cb) {
  var result = 0;
  bg_img.src = './images/map_1_notitle.png';
  pointer_img.src = './images/pointer.png';
  flag_b_green.src = './images/flag_b_green.png';
  flag_s_green.src = './images/flag_s_green.png';
  flag_b_red.src = './images/flag_b_red.png';
  flag_s_red.src = './images/flag_s_red.png';

  bg_img.onload = handleOnLoad;
  pointer_img.onload = handleOnLoad;
  flag_b_green.onload = handleOnLoad;
  flag_s_green.onload = handleOnLoad;
  flag_b_red.onload = handleOnLoad;
  flag_s_red.onload = handleOnLoad;

  function handleOnLoad () {
    result++;
    if(result === imgCount) {
      cb();
      result = null;
    }
  }
}

/**
 * 整合背景和指针的绘制
 */
function drawAll (ctx, ops) {
  ctx.save();
  ctx.drawImage(bg_img, 0, 0, c.width, c.height);
  drawPointer(ctx, ops.opsPointer);
  drawFlags(ctx, ops.opsFlag);
  ctx.restore();
}
// 指针绘制
function drawPointer (ctx, ops) {
  ctx.drawImage(pointer_img, ops.x, ops.y, config.pointer_width, config.pointer_height);
}
// 旗帜绘制
function drawFlags (ctx, ops) {
  for(var i = 0; i < flagArray.length; i += 1) {
    var curFlag = flagArray[i];
    if(i === flagArray.length - 1) {
      curFlag.draw(ctx, curFlag.x, ops.y || curFlag.y);
    } else {
      curFlag.draw(ctx, curFlag.x, curFlag.y);
    }
  }
}


/**
 * 检查点动画处理分发
 */
function checkpointDistribute () {
  if(checkpoint === 11) {
    animation_jump(checkpoint - 2);
  } else {
    animation_jump(checkpoint - 1); 
  }
}

/**
 * 到下一步检查点
 */
function toNextCheckPoint () {
  checkpoint++;
  animation_move(checkpoint, checkpointDistribute);
}

// 动画——原地弹跳
function animation_jump (_checkpoint) {
  var pointer_animation_ops = {
    y: config[_checkpoint].pointer_static_y
  };
  var tween = new TWEEN.Tween(pointer_animation_ops)
    .to({
      y: config[_checkpoint].pointer_static_y + config.pointer_move_height
    })
    .repeat(Infinity)
    .yoyo(true)
    .easing(TWEEN.Easing.Sinusoidal.InOut)
    .onUpdate(function (option) {
      if(!isNaN(option.y)) {
        drawAll(ctx, {
          opsPointer: {
            x: config[_checkpoint].pointer_static_x,
            y: option.y
          },
          opsFlag: {}
        })
      }
    });

  tween.start();

  (function loop (time) {
    var id = requestAnimationFrame(loop);
    var result = tween.update(time);
    if(!result || _checkpoint === checkpoint - 2){
      cancelAnimationFrame(id);
      tween = null;
    }
  })();
}

// 动画——移动
function animation_move (_checkpoint, cb) {
  var pointer_animation_ops = {
    x: config[_checkpoint - 2].pointer_static_x,
    y: config[_checkpoint - 2].pointer_static_y
  };
  var curFlag = flagArray[flagArray.length - 1];
  var flag_animation_ops = {
    y: curFlag.y
  }
  var tweenGroup = new TWEEN.Group();
  var tweenPoint = new TWEEN.Tween(pointer_animation_ops, tweenGroup)
    .to({
      x: config[_checkpoint - 1] ? config[_checkpoint - 1].pointer_static_x : pointer_animation_ops.x,
      y: config[_checkpoint - 1] ? config[_checkpoint - 1].pointer_static_y : pointer_animation_ops.y
    }, 600)
    .easing(TWEEN.Easing.Sinusoidal.InOut)
    .onUpdate(function (ops) {
      if(!isNaN(ops.x) && !isNaN(ops.y)) {
        drawAll(ctx, {
          opsPointer: {
            x: ops.x,
            y: ops.y
          },
          opsFlag: {}
        })
      }
    });
  var tweenFlag = new TWEEN.Tween(flag_animation_ops, tweenGroup)
    .to({
      y: curFlag.y + Flag.top_offset
    }, 800)
    .easing(TWEEN.Easing.Elastic.In)
    .onUpdate(function (ops) {
      if(typeof ops.y === 'number') {
        drawAll(ctx, {
          opsPointer: {
            x: config[_checkpoint - 2].pointer_static_x,
            y: config[_checkpoint - 2].pointer_static_y
          },
          opsFlag: {
            y: ops.y
          }
        })
      }
    });

  tweenFlag.chain(tweenPoint);
  tweenFlag.start();

  (function loop(time){
    var id = requestAnimationFrame(loop);
    var result = tweenGroup.update(time);
    if(!result) {
      cancelAnimationFrame(id);
      tweenGroup.removeAll();
      cb();
    }
  })()
}

// 动画--下坠

/**
 * 检查是否点击在当前指针内部
 */
function checkClickPointer (x, y) {
  var curPointer = config[checkpoint - 1];
  var innerX = x >= curPointer.pointer_static_x * zoomX && x <= curPointer.pointer_static_x * zoomX + config.pointer_width * zoomX;
  var innerY = y >= curPointer.pointer_static_y * zoomY && y <= curPointer.pointer_static_y * zoomY + config.pointer_height * zoomY + c.height * .06667 * zoomY;
  return innerX && innerY;
}



/**
 * 主函数
 */
function startGame() {
  drawAll(ctx, {
    opsPointer: {
      x: config[0].pointer_static_x,
      y: config[0].pointer_static_y
    },
    drawFlags: {}
  });

  checkpointDistribute();

  // 事件绑定
  c.addEventListener('click', function (e) {
    e = e || window.event;
    if(checkClickPointer(e.clientX, e.clientY)) {
      var curCheckPoint = config[checkpoint - 1];

      // TODO: 添加旗帜行为函数化
      flagArray.push(new Flag({
        x: curCheckPoint.pointer_static_x - c.width * .032,
        y: curCheckPoint.pointer_static_y - c.height * .0474
      }, 'red', 's'));

      if(checkpoint < 11) {
        toNextCheckPoint();
      }
    }
  });
}

buildConfig();

initImages(startGame);